import React from 'react';
import { Modal, Tree } from 'antd';
import { useEffect } from 'react';
import { useState } from 'react';
import API from '@/api';
const menuModal = ({ visible, onCreate, onCancel, id }) => {
  const [menuList, setMenuList] = useState(null);
  const [checkIds, setCheckIds] = useState([]);
  const [ids, setIds] = useState([]);
  const initState = () => {
    API.getMenuPermissionListByRoleId({ id }).then((res) => {
      if (res?.t) {
        setCheckIds(lookForId(res.t));
        setIds(lookForAllId(res.t));
      }
    });
  };
  const initMenuList = () => {
    API.getMenuPermissionList().then((res) => {
      if (res?.t) {
        setMenuList(res.t);
      }
    });
  };
  const fieldNames = { title: 'name', key: 'id', children: 'children' };
  function lookForId(data = [], arr = []) {
    for (let item of data) {
      if (item.children && item.children.length) {
        lookForId(item.children, arr);
      } else {
        arr.push(item.id);
      }
    }
    return arr;
  }
  function lookForAllId(data = [], arr = []) {
    for (let item of data) {
      arr.push(item.id);
      if (item.children && item.children.length) {
        lookForAllId(item.children, arr);
      }
    }
    return arr;
  }
  useEffect(() => {
    if (visible) {
      initState();
    }
  }, [visible]);
  useEffect(() => {
    initMenuList();
  }, []);
  const onCheck = (checkedKeys, e) => {
    setCheckIds(checkedKeys);
    setIds([...checkedKeys, ...e.halfCheckedKeys]);
  };
  return (
    <Modal
      visible={visible}
      title="角色配置菜单权限"
      okText="确定"
      cancelText="取消"
      onCancel={onCancel}
      maskClosable={false}
      destroyOnClose
      onOk={() => {
        onCreate(ids);
      }}
    >
      <Tree
        checkable
        treeData={menuList}
        fieldNames={fieldNames}
        checkedKeys={checkIds}
        onCheck={onCheck}
      />
    </Modal>
  );
};

export default menuModal;
